<template>
  <div class="art-full-height">
    <!-- 搜索栏 -->
    <ArtSearchBar
      v-model="searchForm"
      :items="formItems"
      :show-expand="true"
      @search="handleSearch"
      @reset="handleResetSearch"
    />

    <ElCard class="art-table-card" shadow="never">
      <ArtTableHeader
        v-model:columns="columnChecks"
        v-model:showSearchBar="showSearchBar"
        :loading="loading"
        @refresh="refreshData"
      >
        <template #left>
          <ElSpace wrap>
            <ElButton type="primary" :icon="Plus" @click="handleAdd"> 新增小区 </ElButton>
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 数据表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
        <!-- 小区图片列（仅显示第一张，若有多张则显示数量提示） -->
        <template #areaPhoto="{ row }">
          <div v-if="row.areaPhoto.length > 0" class="flex items-center gap-2">
            <ElImage
              :src="row.areaPhoto[0].url"
              :preview-src-list="row.areaPhoto.map((item: any) => item.url)"
              preview-teleported
              fit="cover"
              class="w-10 h-10"
            />
            <span v-if="row.areaPhoto.length > 1" class="text-xs text-gray-500 ml-1">
              +{{ row.areaPhoto.length - 1 }}张
            </span>
          </div>
          <span v-else class="no-image">暂无图片</span>
        </template>

        <!-- 单元数 -->
        <template #areaUnitNum="{ row }">
          <ElTag :type="'success'"> {{ row.areaUnitNum }}单元 </ElTag>
        </template>

        <!-- 楼栋数 -->
        <template #areaHouseNum="{ row }">
          <ElTag :type="'success'"> {{ row.areaHouseNum }}栋 </ElTag>
        </template>

        <!-- 显示状态 -->
        <template #areaUpFlag="{ row }">
           <ElTag :style="{ color: row.areaUpFlag === 1 ? '#fa896b' : '#13d1b9' }" :color="row.areaUpFlag === 1 ? '#fdede8' : '#e7fcf8'">
  {{ row.areaUpFlag === 1 ? '隐藏' : '显示' }}
</ElTag>
        </template>
      </ArtTable>

      <!-- 新增/编辑对话框 -->
      <AreaEditDialog
        v-model="editDialogVisible"
        :area-data="currentAreaData"
        @success="handleDialogSuccess"
      />
      
      <!-- 查看对话框 -->
      <AreaViewDialog
        v-model="viewDialogVisible"
        :area-data="currentAreaData"
        ref="viewDialogRef"
      />
    </ElCard>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, h, nextTick } from 'vue'
import { dayjs, ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useTable } from '@/composables/useTable'
import ArtSearchBar from '@/components/core/forms/art-search-bar/index.vue'
import ArtTable from '@/components/core/tables/art-table/index.vue'
import AreaEditDialog from './modules/area-edit-dialog.vue'
import AreaViewDialog from './modules/area-view-dialog.vue'
import { geoAreaGetDataUsingPost, geoAreaPageDataUsingPost, GeoAreaVo, geoAreaDeleteDataUsingPost } from '@/api'
import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
import { useRouter } from 'vue-router'

// 类型定义
interface SearchForm {
  areaName: string
}

interface ButtonMoreItem {
  key: string
  label: string
  icon?: any
  color?: string
  auth?: string
}

// 响应式数据
const searchForm = ref<SearchForm>({
  areaName: ''
})

const editDialogVisible = ref(false)
const viewDialogVisible = ref(false)
const viewDialogRef = ref()
const currentAreaData = ref<GeoAreaVo | null>(null)
const router = useRouter()

// 搜索表单配置
const formItems = computed(() => [
  {
    key: 'areaName',
    label: '小区名称',
    type: 'input',
    props: {
      placeholder: '请输入小区名称',
      clearable: true
    }
  }
])

// 获取小区服务列表（用于修复分页数据中服务列表为null的问题）
const fetchAreaServeList = async (areaId: number): Promise<any[]> => {
  try {
    const res = await geoAreaGetDataUsingPost({
      body: { id: areaId }
    })
    return res?.geoAreaServeList || []
  } catch (error) {
    console.error(`获取小区 ${areaId} 的服务列表失败:`, error)
    return []
  }
}

// 使用 useTable 管理表格数据
const {
  columns,
  columnChecks,
  data,
  loading,
  pagination,
  getData,
  searchParams,
  resetSearchParams,
  handleSizeChange,
  handleCurrentChange,
  refreshData
} = useTable({
  core: {
    apiFn: geoAreaPageDataUsingPost,
    apiParams: {
      body: {
        areaName: searchForm.value.areaName
      }
    },
    paginationWrapper: 'body', // 将分页参数包装到 body 对象中
    columnsFactory: () => [
      {
        prop: 'id',
        label: 'ID',
        width: 80
      },
      {
        prop: 'areaName',
        label: '小区名称',
        width: 150
      },
      {
        prop: 'areaAddress',
        label: '小区地址',
        minWidth: 150,
        showOverflowTooltip: true
      },
      {
        prop: 'areaPhoto',
        label: '小区图片',
        width: 150,
        useSlot: true
      },
      {
        prop: 'areaHouseNum',
        label: '楼栋数',
        width: 90,
        align: 'center',
        headerAlign: 'center',
        useSlot: true
      },
      {
        prop: 'areaUnitNum',
        label: '单元数',
        width: 100,
        align: 'center',
        headerAlign: 'center',
        useSlot: true
      },
      {
        prop: 'areaUpFlag',
        label: '显示状态',
        width: 100,
        align: 'center',
        headerAlign: 'center',
        useSlot: true
      },
      {
        prop: 'createTime',
        label: '创建时间',
        width: 200,
        align: 'center',
        headerAlign: 'center',
        formatter: (row: GeoAreaVo) => dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
      },
      {
        prop: 'operation',
        label: '操作',
        width: 200,
        fixed: 'right',
        align: 'center',
        headerAlign: 'center',
        formatter: (row) => {
          return h('div', { class: 'flex items-center gap-2' }, [
            h(ArtButtonTable, {
              type: 'view',
              onClick: () => handleView(row),
              title: '查看'
            }),
            h(ArtButtonTable, {
              type: 'edit',
              onClick: () => buttonMoreClick({ key: 'edit', label: '编辑' }, row)
            }),
            h(ArtButtonTable, {
              type: 'delete',
              onClick: () => buttonMoreClick({ key: 'delete', label: '删除' }, row)
            }),
            h(ArtButtonTable, {
              label: '小区详情',
              type: 'more',
              plain: true,
              size: 'small',
              onClick: () => handleAreaDetail(row)
            })
          ])
        }
      }
    ]
  },
  hooks: {
    onSuccess: async (tableData: GeoAreaVo[]) => {
      // 处理表格数据，确保服务列表正确显示
      const processedData = await Promise.all(
        tableData.map(async (item: GeoAreaVo) => {
          item.areaPhoto = JSON.parse(item.areaPhoto || '[]')
          return item
        })
      )
      data.value = processedData
    }
  }
})

const showSearchBar = ref(false)

const handleSearch = () => {
  searchParams.body.areaName = searchForm.value.areaName
  getData()
}

const handleResetSearch = () => {
  searchParams.body.areaName = ''
  getData()
}

const handleAdd = () => {
  currentAreaData.value = null
  editDialogVisible.value = true
}

const handleAreaDetail = (row: GeoAreaVo) => {
  router.push(`/area/areaDetail?areaId=${row.id}`)
}

const handleView = async (row: GeoAreaVo) => {
  try {
    const data = await geoAreaGetDataUsingPost({
      body: {
        id: row.id
      }
    })

    if (!data) {
      ElMessage.warning('获取小区详情失败：数据为空')
      return
    }

    currentAreaData.value = data as GeoAreaVo
    
    // 等待DOM更新后再打开对话框
    await nextTick()
    viewDialogVisible.value = true
    
    // 确保组件已渲染并接收到新数据后再调用handleOpen
    await nextTick()
    viewDialogRef.value?.handleOpen()
  } catch (error) {
    console.error('获取小区详情失败:', error)
    ElMessage.error('获取小区详情失败')
  }
}

const buttonMoreClick = async (item: ButtonMoreItem, row: GeoAreaVo) => {
  switch (item.key) {
    case 'view':
      handleView(row)
      break
    case 'edit':
      try {
        const data = await geoAreaGetDataUsingPost({
          body: {
            id: row.id
          }
        })
        currentAreaData.value = data as GeoAreaVo
        editDialogVisible.value = true
      } catch (error) {
        console.error('获取编辑数据失败:', error)
        ElMessage.error('获取小区详情失败')
      }
      break
    case 'delete':
      await handleDelete(row)
      break
  }
}

const handleDelete = async (row: GeoAreaVo) => {
  try {
    await ElMessageBox.confirm(`确定要删除小区"${row.areaName}"吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await geoAreaDeleteDataUsingPost({ body: { id: row.id } })
    ElMessage.success('删除成功')
    getData()
  } catch (error) {
    console.log('删除被取消或出错:', error)
  }
}

const handleDialogSuccess = () => {
  editDialogVisible.value = false
  currentAreaData.value = null
  getData()
}
</script>

<style lang="scss" scoped>
  .services-list {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
  }

  .service-tag {
    margin: 2px;
  }

  .no-image {
    font-size: 12px;
    color: rgb(var(--art-text-gray-500));
  }

</style>